package com.lbj.controller;

import com.lbj.domain.Comment;
import com.lbj.domain.Topic;
import com.lbj.domain.User;
import com.lbj.service.CommentService;
import com.lbj.service.TopicService;
import com.lbj.service.UserService;
import com.lbj.service.impl.CommentServiceImpl;
import com.lbj.service.impl.TopicServiceImpl;
import com.lbj.service.impl.UserServiceImpl;
import com.lbj.utils.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

public class UserController extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private TopicService topicService = new TopicServiceImpl();
    private CommentService commentService = new CommentServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if("/user/login.do".equals(path)){
            login(request,response);
        } else if("/user/logout.do".equals(path)){
            logout(request,response);
        }else if("/user/register.do".equals(path)){
            register(request,response);
        }else if("/user/getTopics.do".equals(path)){
            getTopics(request,response);
        }else if("/user/login/getVerifyCode.do".equals(path)){
            getVerifyCode(request,response);
        }else if("/user/releaseTopic.do".equals(path)){
            releaseTopic(request,response);
        }else if("/user/getTopicById.do".equals(path)){
            getTopicById(request,response);
        }else if("/user/releaseComment.do".equals(path)){
            releaseComment(request,response);
        }else if("/user/thumb.do".equals(path)){
            thumb(request,response);
        }else if("/user/collection.do".equals(path)){
            collection(request,response);
        }else if("/user/pageList.do".equals(path)){
            pageList(request,response);
        }
    }

    private void pageList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));    // 想要跳转的页面
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));  // 每页记录数目

        Map<Topic,User> topicUserMap = new LinkedHashMap<>();
        List<Topic> topics = topicService.pageList(pageNum,pageSize);

        for (Topic topic : topics) {
            User user = userService.getUserById(topic.getCreateBy());
            topicUserMap.put(topic,user);
        }

        int totalCount = topicService.getTotalCount();
        int totalPage = topicService.getTotalPage(totalCount,pageSize);

        // 置顶的
        Map<Topic,User> topicUserMapTop = new LinkedHashMap<>();
        List<Topic> topicsTop = topicService.getTopicsTop();
        for (Topic topic : topicsTop) {
            User user = userService.getUserById(topic.getCreateBy());
            topicUserMapTop.put(topic,user);
        }



        session.setAttribute("topicUserMap",topicUserMap);
        session.setAttribute("topicUserMapTop",topicUserMapTop);
        session.setAttribute("pageNum", pageNum);
        session.setAttribute("pageSize", pageSize);
        session.setAttribute("totalPage", totalPage);
        session.setAttribute("totalCount", totalCount);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("success",true);
        PrintJson.printJsonObj(response, map);

    }

    private void collection(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();

        String topicId = request.getParameter("topicId");
        String userId = ((User)session.getAttribute("user")).getId();
        Topic topic = topicService.getTopicById(topicId);
        topic.setCollectionId(topic.getCollectionId()+","+userId);
        topic.setCollectionCount(topic.getCollectionCount()+1);
        Boolean flag = topicService.updateInfo(topic);

        PrintJson.printJsonFlag(response,flag);
    }

    private void thumb(HttpServletRequest request, HttpServletResponse response) {
        // 未实现 取消点赞功能
        HttpSession session = request.getSession();

        String topicId = request.getParameter("topicId");
        String userId = ((User)session.getAttribute("user")).getId();
        Topic topic = topicService.getTopicById(topicId);
        topic.setThumbsId(topic.getThumbsId()+","+userId);
        topic.setThumbsCount(topic.getThumbsCount()+1);

        Boolean flag = topicService.updateInfo(topic);

        PrintJson.printJsonFlag(response,flag);

    }

    private void releaseComment(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();

        // 得到数据封装对象
        String commentContent = request.getParameter("commentContent");
        String topicId = request.getParameter("topicId");
        String userId = ((User)session.getAttribute("user")).getId();
        String id = UUIDUtil.getUUID();
        String createTime = DateTimeUtil.getSysTime();
        Comment comment = new Comment(id,EmojiDealUtil.changeEmojiToHtml(commentContent),topicId,userId,createTime);

        // 调用service
        boolean flag = commentService.addComment(comment);

        if(flag == true) {
            // 评论次数+1
            Topic topic = topicService.getTopicById(topicId);
            topic.setCommentCount(topic.getCommentCount() + 1);
            topicService.updateInfo(topic);
        }
        // 将处理结果发回前端
        PrintJson.printJsonFlag(response,flag);

    }

    private void getTopicById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();


        String id= request.getParameter("id");

        Topic topic = topicService.getTopicById(id);
        String userId = ((User)(request.getSession().getAttribute("user"))).getId();
        User user = userService.getUserById(topic.getCreateBy());

        if(!userId.equals(topic.getCreateBy())){ // 观看用户不是发布者
            topic.setBrowseCount(topic.getBrowseCount()+1); // 浏览次数+1
            topicService.updateInfo(topic);
        }
        List<Topic> topics = topicService.getTopics();
        int topicCount =topicService.getUserTopicCount(topics);
        int collectionCount = topicService.geUserCollectionCount(topics);
        int thumbCount = topicService.getUserThumbCount(topics);

        // 获得该帖子的所有评论
        Map<Comment,User> commentUserMap = new LinkedHashMap<>();
        List<Comment> comments = commentService.getComments(id);
        for (Comment comment : comments) {
            User u = userService.getUserById(comment.getUserId());
            commentUserMap.put(comment,u);
        }

        request.setAttribute("topic",topic);
        request.setAttribute("user",user);
        request.setAttribute("commentUserMap",commentUserMap);
        request.setAttribute("topicCount",topicCount);
        request.setAttribute("collectionCount",collectionCount);
        request.setAttribute("thumbCount",thumbCount);

        request.getRequestDispatcher("/topicInfo.jsp").forward(request,response);
    }

    private void releaseTopic(HttpServletRequest request, HttpServletResponse response) {
        String id = UUIDUtil.getUUID();
        String title = request.getParameter("topicTitle");
        String content = request.getParameter("topicContent");
        String status = "00";
        String createTime = DateTimeUtil.getSysTime();
        String createBy = ((User)request.getSession().getAttribute("user")).getId();
        int browseCount = 0;
        int thumbsCount = 0;
        int commentCount = 0;
        int collectionCount = 0;
        String thumbsId="";
        String collectionId="";
        Topic topic = new Topic(id,title,EmojiDealUtil.changeEmojiToHtml(content),status,createTime,
                createBy,browseCount,thumbsCount,commentCount,collectionCount,thumbsId,collectionId);

        Boolean flag = topicService.addTopic(topic);
        if(flag == false){
            PrintJson.printJsonFlag(response, false);
        }else {
            PrintJson.printJsonFlag(response,true);
        }
    }

    private void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        int width=200;
        int height=69;
        BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
        request.getSession().setAttribute("verifyCode", randomText);
        response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别
        try {
            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg,"png",os);//输出图片流
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void register(HttpServletRequest request, HttpServletResponse response) {
        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String uuid = UUIDUtil.getUUID();
        String lockState = "1";
        String createTime = DateTimeUtil.getSysTime();
        loginPwd = MD5Util.getMD5(loginPwd);
        String profilePhoto = request.getContextPath()+"/static/image/touxiang.jpg"; // 默认头像
        User user = new User(uuid,loginAct,name,loginPwd,email,lockState,createTime,profilePhoto);
        boolean flag = false;
        flag = userService.register(user);
        if(flag != false){ // 注册成功
            PrintJson.printJsonFlag(response, true);
        }else {
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg", "注册失败");
            PrintJson.printJsonObj(response, map);
        }

    }

    private void logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        PrintJson.printJsonFlag(response, true);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        loginPwd = MD5Util.getMD5(loginPwd);    // 密码加密
        String verifyCode = (String) request.getSession().getAttribute("verifyCode");
        String inputVerifyCode = request.getParameter("verifyCode");

        if(!verifyCode.equals(inputVerifyCode)){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg", "验证码错误");
            PrintJson.printJsonObj(response, map);
            return;
        }
        User user = userService.login(loginAct,loginPwd);
        if(user == null) { // 未查找到用户
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg", "账号或密码不正确");
            PrintJson.printJsonObj(response, map);

        }else if("0".equals(user.getLockState())){  // 账号被锁定
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg", "该账号已被锁定");
            PrintJson.printJsonObj(response, map);
        }else {
            request.getSession().setAttribute("user", user);
            PrintJson.printJsonFlag(response, true);
        }
    }
    private void getTopics(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session = request.getSession();
        // 未置顶的
         Map<Topic,User> topicUserMap = new LinkedHashMap<>();
        List<Topic> topics = topicService.getTopics();
        for (Topic topic : topics) {
            User user = userService.getUserById(topic.getCreateBy());
            topicUserMap.put(topic,user);
        }

        // 置顶的
        Map<Topic,User> topicUserMapTop = new LinkedHashMap<>();
        List<Topic> topicsTop = topicService.getTopicsTop();
        for (Topic topic : topicsTop) {
            User user = userService.getUserById(topic.getCreateBy());
            topicUserMapTop.put(topic,user);
        }

        session.setAttribute("topicUserMap",topicUserMap);
        session.setAttribute("topicUserMapTop",topicUserMapTop);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("success",true);
        PrintJson.printJsonObj(response, map);


    }

}
